package com.gsoe.judge.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.gsoe.base.exception.JudgeException;
import com.gsoe.base.exception.ProblemException;
import com.gsoe.base.model.MqMessage;
import com.gsoe.base.model.Result;
import com.gsoe.base.model.User;
import com.gsoe.base.utils.UserUtil;
import com.gsoe.dto.SaveCacheDTO;
import com.gsoe.judge.client.ProblemClient;
import com.gsoe.judge.mapper.ExamCacheMapper;

import com.gsoe.judge.service.ExamCacheService;
import com.gsoe.po.ExamCache;
import lombok.Synchronized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 考试答题缓存 服务实现类
 * </p>
 *
 * @author xiaoma
 * @since 2024-11-04
 */
@Service
public class ExamCacheServiceImpl extends ServiceImpl<ExamCacheMapper, ExamCache> implements ExamCacheService {
    @Autowired
    ProblemClient problemClient;


    @Override
    public void delByTextId(Long examId) {
        remove(new QueryWrapper<ExamCache>()
                .eq("exam_id", examId)
        );
    }

    @Override
    public Map<Long, String> getExamCache(Long examId,Long userId) {
        List<ExamCache> examCacheList = lambdaQuery()
                .eq(ExamCache::getExamId, examId)
                .eq(ExamCache::getUserId, userId)
                .list();
        if(CollectionUtil.isEmpty(examCacheList)){
            return Map.of();
        }
        return examCacheList.stream().collect(Collectors.toMap(ExamCache::getProblemId,ExamCache::getInput));
    }

    @Override
    public boolean saveInput(SaveCacheDTO saveCacheDTO) {
        Result<Long> examRemainingTime;
        Long userId = UserUtil.getLoginUser().getId();
        try {
            examRemainingTime = problemClient.getExamRemainingTime(saveCacheDTO.getId(),userId);
            if(examRemainingTime.getCode() != 200){
                throw new RuntimeException(examRemainingTime.getMsg());
            }
        }catch (Exception e){
            throw new ProblemException("saveInput:"+e.getMessage());
        }
        if(examRemainingTime.getData()<0){
            return false;
        }

        ExamCache examCache = lambdaQuery()
                .eq(ExamCache::getUserId, userId)
                .eq(ExamCache::getExamId, saveCacheDTO.getId())
                .eq(ExamCache::getProblemId,saveCacheDTO.getProblemId())
                .one();


        if(examCache==null) examCache = new ExamCache();
        examCache.setExamId(saveCacheDTO.getId());
        examCache.setInput(saveCacheDTO.getInput());
        examCache.setProblemId(saveCacheDTO.getProblemId());
        examCache.setUserId(userId);
        saveOrUpdate(examCache);
        return true;
    }

    @Override
    //1、examId
    //2、userList
    public Map<Long, Map<Long, String>> getExamCacheByUserList(MqMessage mqMessage) {
        Long examId = Long.valueOf((String) mqMessage.getData1());
        if(examId==null){throw new JudgeException("getExamCacheByUserList:id不能为空");}
        List<Long> userList = (List<Long>) mqMessage.getData2();

        if(CollectionUtil.isEmpty(userList)){return Map.of();}

        List<ExamCache> examCacheList = lambdaQuery().eq(ExamCache::getExamId, examId)
                .in(ExamCache::getUserId, userList)
                .list();

        if(CollectionUtil.isEmpty(examCacheList)){return Map.of();}

        return examCacheList.stream()
                .collect(Collectors.toMap(
                        ExamCache::getUserId,
                        examCache -> new HashMap<Long, String>() {{
                            put(examCache.getProblemId(), examCache.getInput());
                        }},
                        (map, examCache) -> {
                            map.putAll(examCache);
                            return map;
                        }
                ));

    }
}
